package cn.tedu.wechatdemo.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.tedu.wechatdemo.dto.WeChatDTO;
import cn.tedu.wechatdemo.entity.Account;
import cn.tedu.wechatdemo.entity.Token;
import cn.tedu.wechatdemo.entity.UserInfo;
import cn.tedu.wechatdemo.utils.HttpRequestUtil;
import cn.tedu.wechatdemo.utils.WeChatUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * @Author: Miyako
 * @Date: 2024-10-15-8:29
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/weChat")
public class WeChatController {
    @Autowired
    Account account;



    //微信接口测试类
    @GetMapping("check")
    public String checkWeChat( WeChatDTO weChatDTO)  {
        WeChatUtils weChatUtils = new WeChatUtils("Pudding",weChatDTO);
        String echoStr = weChatUtils.checkWeChatToken();
        return echoStr;
    }


    //跨域注解
    @CrossOrigin
    @GetMapping("qrCode")
    public String getQrCode(){
        int width = 200;
        int height = 200;
        String content = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state= 123#wechat_redirect";

        content = content.replace("APPID", account.getAppId()).replace("REDIRECT_URI", account.getDomain() + account.getRedirectUri());
        //设置二维码的宽高
        QrConfig config = new QrConfig(width,height);
        //设置二维码颜色
        config.setForeColor(Color.green);
        //设置二维码中心图片
        config.setImg(FileUtil.file("Pudding.png"));
        File file = FileUtil.file("D:\\img\\weChatQr");
        //参数依次为 转为二维码的内容，二维码配置，本地存储路径
        //将生成的二维码图片转为用base64编码的字符串返回给前端
        String QrPNG = QrCodeUtil.generateAsBase64(content, config, "png");
        return QrPNG;
    }

    @GetMapping("/login")
    public  String login (String code , String state){

        String url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

        url = url.replace("APPID", account.getAppId()).replace("SECRET", account.getAppSecret()).replace("CODE",code);

        HttpResponse httpResponse = HttpRequestUtil.doGet(url);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            System.out.println(statusCode);
            //获取到数据的报文格式
            HttpEntity entity = httpResponse.getEntity();
            String entityStr = null;
            try {
                //将报文格式转为json格式的字符串
                 entityStr = EntityUtils.toString(entity);
                 //将json字符串转化为token对象
                Token token = JSON.parseObject(entityStr, Token.class);
                String accessToken = token.getAccess_token();
                String openid = token.getOpenid();
                //再发送一个请求获取用户信息
                url="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
                //替换token 和openid
                url=url.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openid);
                HttpResponse responseHttp = HttpRequestUtil.doGet(url);
                int stCode = responseHttp.getStatusLine().getStatusCode();
                if (stCode == 200){
                    HttpEntity httpEntity = responseHttp.getEntity();
                    String userInfoStr = EntityUtils.toString(httpEntity);
                    UserInfo userInfo = JSON.parseObject(userInfoStr, UserInfo.class);
                    log.debug("登录的用户信息为{}",userInfo);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return "success";
        }
        return "defeat";
    }

}
